<template>
  <div>
    <el-dialog
      width="90%"
      title="编辑全景"
      :visible.sync="dialogFormVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      v-dialogDrag
    >
      <el-row :gutter="24" style="height: 500px; overflow-y: auto">
        <el-col :span="4">
          <div
            class="listItem"
            :class="indexNum === index ? 'active' : ''"
            v-for="(item, index) in vrList"
            :key="item.id"
            @click="upDateVrView(item, index)"
          >
            <p>节点{{ item.id }}方向</p>
          </div>
        </el-col>
        <el-col :span="20">
          <div
            id="pannellum"
            v-if="viewerShow"
            style="width: 100%; height: 400px; margin-bottom: 10px"
          ></div>
          <file-upload
            text="上传全景图片"
            :limit="1"
            @input="uploadFile"
            :fileListShow="false"
            :fileType="['jpg', 'png', 'jpeg']"
            ref="uploadRef"
          ></file-upload>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" v-if="markerInfo.isEdit" @click="deleteNodeVr"
          >删除全景</el-button
        >
        <el-button @click="cancle(1)">取 消</el-button>
        <el-button type="primary" @click="confirm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addVr, updateVr, delVr, getNodeVrInfo } from "@/api/map/vr.js";

export default {
  data() {
    return {
      viewer: null, // 声明一个视图对象，以便后期全局进行组件的操作
      currentMarker: null, //
      imgurl: "", // 全景图的图片
      fileList: [],
      indexNum: 0,
      viewerShow: false,
      dialogFormVisible: false,
      vrList: [],
      arrowIndex: 1,
      arrowImage: require("@/assets/images/arrowUp.png"),
    };
  },
  props: {
    dialogShow: Boolean,
    markerInfo: Object,
    closeDialog: {
      type: Function,
      require: true,
      default: null,
    },
  },

  /**
   * 生命周期函数--在组件挂载完毕后被调用
   * 这里可以进行一些初始化操作
   * 例如：this.viewerInit();
   */
  methods: {
    viewerInit() {
      console.log(this.vrList[this.indexNum]);
      if (!this.imgurl) return;
      this.viewerShow = true;
      this.$nextTick(() => {
        this.viewer = pannellum.viewer("pannellum", {
          type: "equirectangular",
          panorama: this.imgurl,
          autoLoad: true,
          // showControls: true,
        });
        let clickTimeout;
        // 添加 mousedown 事件监听器
        this.viewer.on("mousedown", function (event) {
          // 清除之前的超时，防止重复触发
          if (clickTimeout) {
            clearTimeout(clickTimeout);
          }
          // 设置一个新的超时来等待 mouseup 事件
          clickTimeout = setTimeout(() => {
            // 如果超过阈值时间没有 mouseup，则取消这次点击
            clickTimeout = null;
          }, 200);
        });
        this.viewer.on("mouseup", (event) => {
          // 将鼠标事件转换为全景图中的坐标 (yaw, pitch)
          if (!clickTimeout) return;
          clearTimeout(clickTimeout); // 清除超时
          clickTimeout = null;
          var coordinates = this.viewer.mouseEventToCoords(event);
          if (coordinates) {
            var yaw = coordinates[1];
            var pitch = coordinates[0];

            this.vrList[this.indexNum].yaw = yaw;
            this.vrList[this.indexNum].pitch = pitch;
            this.updateMarkerPitch(pitch, yaw);
          }
        });
        setTimeout(() => {
          this.updateMarkerPitch(
            this.vrList[this.indexNum].pitch,
            this.vrList[this.indexNum].yaw
          );
        }, 500);
      });
    },
    updateMarkerPitch(pitch, yaw) {
      console.log(pitch, yaw);
      this.viewer.removeHotSpot("current-marker");
      this.$nextTick(() => {
        // 创建新的标记配置
        const newHotSpot = {
          id: "current-marker",
          pitch,
          yaw,
          cssClass: "custom-hotspot",
        };
        // 添加新的标记并保存引用
        this.viewer.addHotSpot(newHotSpot);
        this.viewer.setPitch(pitch * 1);
        this.viewer.setYaw(yaw * 1);
      });
    },
    /**
     * 选择某个方向
     * @param {Object} item 当前选择的方向
     * @param {Number} index 选择的方向的下标
     */
    upDateVrView(item, index) {
      console.log(item);
      if (this.indexNum == index) return;
      this.arrowIndex = item.arrowIndex;
      this.indexNum = index;
      if (!this.viewer) return;
      this.updateMarkerPitch(item.pitch, item.yaw);
    },

    // 上传全景图回调
    uploadFile(e, fileList) {
      if (e) {
        this.imgurl = fileList[0].url;
        if (this.viewer) this.viewer.destroy();
        this.viewerInit();
      }
    },
    // 关闭对话框 根据index判断是保存还是取消
    cancle(index, param) {
      this.$refs["uploadRef"]._data.fileList = [];
      this.viewerShow = false;
      this.closeDialog(index, param);
    },
    // 保存该节点vr信息
    confirm() {
      if (!this.imgurl) return this.$modal.msgError(`请上传全景图片!`);
      const params = {
        vrId: this.markerInfo.vrId,
        nodeId: this.markerInfo.id,
        pic: this.imgurl,
        vrParams: [],
      };
      this.vrList.forEach((item) => {
        params.vrParams.push({
          nodeId: item.id,
          param1: item.yaw,
          param2: item.pitch,
          param3: item.arrowIndex,
        });
      });
      console.log(this.imgurl);
      if (this.markerInfo.isEdit) {
        this.updateNodeVr(params);
      } else {
        this.addNodeVr(params);
      }
      this.cancle(2, params);
    },
    // 添加该节点vr信息
    addNodeVr(data) {
      addVr(data).then((res) => {
        console.log(res);
      });
    },
    // 修改该节点vr信息
    updateNodeVr(data) {
      console.log(data);
      console.log(this.markerInfo.vrId);
      updateVr(data).then((res) => {
        console.log(res);
      });
    },
    // 删除该节点vr信息
    deleteNodeVr() {
      // const data = {
      //   vrIds: this.markerInfo.vrId,
      // };
      // console.log(data);
      this.$modal.loading();
      delVr(this.markerInfo.vrId).then((res) => {
        console.log(res);
        this.cancle(3);
        this.$modal.closeLoading();
      });
    },

    // 获取节点vr信息
    getMarkers() {
      this.$nextTick(async () => {
        if (this.markerInfo.isEdit) {
          await getNodeVrInfo({
            nodeId: this.markerInfo.id,
          }).then((res) => {
            console.log(res.data[0]);
            this.markerInfo["vrId"] = res.data[0].vrId;
            this.imgurl = res.data[0].pic;
            res.data[0].vrParams.forEach((e) => {
              this.vrList.push({
                id: e.nodeId,
                yaw: e.param1,
                pitch: e.param2,
                arrowIndex: e.param3 || 1,
              });
            });
            this.arrowIndex = res.data[0].vrParams[0].param3 || 1;
          });
        } else {
          this.imgurl = "";
          this.arrowIndex = 1;
          this.markerInfo.list.forEach((id) => {
            this.vrList.push({
              id,
              yaw: 0,
              pitch: 0,
              arrowIndex: 1,
            });
          });
        }
        this.viewerInit();
      });
    },
  },
  watch: {
    dialogShow(newVal) {
      this.dialogFormVisible = newVal;
      if (newVal) {
        this.indexNum = 0;
        this.vrList = [];
        this.getMarkers();
      }
    },
  },
};
</script>
<style scoped lang="scss">
.listItem {
  display: flex;
  align-items: center;
  font-size: 14px;
  border: 1px solid #ccc;
  min-width: 130px;
  text-align: center;
  justify-content: space-between;
  height: 40px;
  padding: 0 10px;
  box-sizing: border-box;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 10px;
  text-align: center;
}
.active {
  background-color: #46a6ff;
  color: #fff;
}
</style>
